package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.config.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.config.CacheService;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {


    @Autowired
    CacheService cacheService;


    /**
     * 用户关注/取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1 参数校验
        if (dto==null || dto.getAuthorApUserId()==null
                ||   dto.getOperation() < 0 || dto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 获取当前登录人的apuser id
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer apUserId = apUser.getId();  // 当前登录APP端用户id

        Integer followId = dto.getAuthorApUserId(); // 被关注的作者对应用户id

        //3 判断是否已关注
        if (dto.getOperation() == 0) {
            Double score = cacheService.zScore(UserRelationConstants.FOLLOW_LIST + apUserId, followId.toString());
            if (score != null) {
                CustException.cust("已关注，无需重复关注");
            }

            //4 关注 follow:id   fans:id
            // 将对方写入我的关注中
            cacheService.zAdd(UserRelationConstants.FOLLOW_LIST + apUserId, followId.toString(), System.currentTimeMillis());
            // 将我写入对方的粉丝中
            cacheService.zAdd(UserRelationConstants.FANS_LIST + followId, apUserId.toString(), System.currentTimeMillis());

        }else {
            //5 取消关注
            cacheService.zRemove(UserRelationConstants.FOLLOW_LIST + apUserId, followId.toString());
            cacheService.zRemove(UserRelationConstants.FANS_LIST + followId, apUserId.toString());
        }

        // TODO 文章id，大数据需要 消息发送给对应的接口

        //6 返回
        return ResponseResult.okResult();
    }
}
